#!/usr/bin/env node

/**
 * 测试1060指令的逻辑实现
 * 模拟BasicItemService和验证返回格式
 */

class MockBasicItemService {
    constructor() {
        // 模拟数据库中的药品数据
        this.medicines = {
            20: {
                id: 20,
                name: "菖蒲酒",
                silverPrice: 2000,
                lv: 4,
                description: "甜而不腻，辣而不呛，有清头明目、轻身坚骨之功。乃恢复精力之佳酿。",
                status: 1
            },
            1: {
                id: 1,
                name: "跌打药",
                silverPrice: 50,
                lv: 1,
                description: "散瘀消肿，强筋健骨，可迅速补充气血。",
                status: 1
            },
            17: {
                id: 17,
                name: "回春汤",
                silverPrice: 100,
                lv: 2,
                description: "治疗外伤的良药，可快速恢复生命值。",
                status: 1
            }
        };
    }

    async getItemById(id) {
        return this.medicines[id] || null;
    }
}

class MedicineInfoHandler {
    constructor() {
        this.basicItemService = new MockBasicItemService();
    }

    async handleMedicineInfoQuery(payload) {
        try {
            const { gid } = payload;

            // 验证参数
            if (!gid || typeof gid !== "number") {
                return {
                    act_id: 1060,
                    code: -1,
                    msg: "药品ID不能为空且必须为数字",
                    data: [],
                };
            }

            // 查询药品信息
            const item = await this.basicItemService.getItemById(gid);

            if (!item) {
                return {
                    act_id: 1060,
                    code: -1,
                    msg: "药品不存在",
                    data: [],
                };
            }

            // 构建返回数据格式
            const data = [
                { k: "名称:", v: item.name },
                { k: "精力值:", v: item.silverPrice?.toString() || "0" },
                { k: "等级:", v: item.lv?.toString() || "1" },
                { k: "介绍:", v: item.description || "暂无介绍" },
            ];

            return {
                act_id: 1060,
                code: 0,
                data: data,
            };
        } catch (error) {
            console.error("处理药品信息查询指令1060失败:", error);
            return {
                act_id: 1060,
                code: -1,
                msg: "查询失败",
                data: [],
            };
        }
    }
}

class MedicineInfoTester {
    constructor() {
        this.handler = new MedicineInfoHandler();
        this.testResults = [];
    }

    addTestResult(testName, success, message, expected, actual) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message,
            expected: expected,
            actual: actual
        });
    }

    async testValidMedicineQuery() {
        console.log('\n🧪 测试1: 有效药品查询');

        const payload = { gid: 20 };
        const result = await this.handler.handleMedicineInfoQuery(payload);

        console.log('📤 请求:', JSON.stringify(payload, null, 2));
        console.log('📨 响应:', JSON.stringify(result, null, 2));

        // 验证响应格式
        const isValid = result.act_id === 1060 &&
            result.code === 0 &&
            Array.isArray(result.data) &&
            result.data.length === 4 &&
            result.data[0].k === "名称:" &&
            result.data[0].v === "菖蒲酒" &&
            result.data[1].k === "精力值:" &&
            result.data[1].v === "2000";

        this.addTestResult(
            '有效药品查询',
            isValid,
            isValid ? '查询成功' : '查询失败',
            'act_id: 1060, code: 0, data包含4个字段',
            `act_id: ${result.act_id}, code: ${result.code}, data长度: ${result.data.length}`
        );
    }

    async testNonExistentMedicine() {
        console.log('\n🧪 测试2: 不存在的药品查询');

        const payload = { gid: 99999 };
        const result = await this.handler.handleMedicineInfoQuery(payload);

        console.log('📤 请求:', JSON.stringify(payload, null, 2));
        console.log('📨 响应:', JSON.stringify(result, null, 2));

        // 验证错误响应
        const isValid = result.act_id === 1060 &&
            result.code === -1 &&
            result.msg === "药品不存在" &&
            Array.isArray(result.data) &&
            result.data.length === 0;

        this.addTestResult(
            '不存在药品查询',
            isValid,
            isValid ? '正确处理' : '处理错误',
            'act_id: 1060, code: -1, msg: "药品不存在"',
            `act_id: ${result.act_id}, code: ${result.code}, msg: "${result.msg}"`
        );
    }

    async testInvalidGidType() {
        console.log('\n🧪 测试3: 无效GID类型');

        const payload = { gid: "invalid" };
        const result = await this.handler.handleMedicineInfoQuery(payload);

        console.log('📤 请求:', JSON.stringify(payload, null, 2));
        console.log('📨 响应:', JSON.stringify(result, null, 2));

        // 验证错误响应
        const isValid = result.act_id === 1060 &&
            result.code === -1 &&
            result.msg === "药品ID不能为空且必须为数字" &&
            Array.isArray(result.data) &&
            result.data.length === 0;

        this.addTestResult(
            '无效GID类型',
            isValid,
            isValid ? '正确处理' : '处理错误',
            'act_id: 1060, code: -1, msg: "药品ID不能为空且必须为数字"',
            `act_id: ${result.act_id}, code: ${result.code}, msg: "${result.msg}"`
        );
    }

    async testMissingGid() {
        console.log('\n🧪 测试4: 缺少GID参数');

        const payload = {};
        const result = await this.handler.handleMedicineInfoQuery(payload);

        console.log('📤 请求:', JSON.stringify(payload, null, 2));
        console.log('📨 响应:', JSON.stringify(result, null, 2));

        // 验证错误响应
        const isValid = result.act_id === 1060 &&
            result.code === -1 &&
            result.msg === "药品ID不能为空且必须为数字" &&
            Array.isArray(result.data) &&
            result.data.length === 0;

        this.addTestResult(
            '缺少GID参数',
            isValid,
            isValid ? '正确处理' : '处理错误',
            'act_id: 1060, code: -1, msg: "药品ID不能为空且必须为数字"',
            `act_id: ${result.act_id}, code: ${result.code}, msg: "${result.msg}"`
        );
    }

    async testAnotherValidMedicine() {
        console.log('\n🧪 测试5: 另一个有效药品查询');

        const payload = { gid: 1 };
        const result = await this.handler.handleMedicineInfoQuery(payload);

        console.log('📤 请求:', JSON.stringify(payload, null, 2));
        console.log('📨 响应:', JSON.stringify(result, null, 2));

        // 验证响应格式
        const isValid = result.act_id === 1060 &&
            result.code === 0 &&
            Array.isArray(result.data) &&
            result.data.length === 4 &&
            result.data[0].k === "名称:" &&
            result.data[0].v === "跌打药" &&
            result.data[1].v === "50";

        this.addTestResult(
            '另一个有效药品查询',
            isValid,
            isValid ? '查询成功' : '查询失败',
            'act_id: 1060, code: 0, data包含跌打药信息',
            `act_id: ${result.act_id}, code: ${result.code}, 药品名称: ${result.data[0]?.v}`
        );
    }

    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(80));

        let successCount = 0;
        let totalCount = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
            if (!result.success) {
                console.log(`   期望: ${result.expected}`);
                console.log(`   实际: ${result.actual}`);
            }
            if (result.success) successCount++;
        });

        console.log('='.repeat(80));
        console.log(`总计: ${successCount}/${totalCount} 测试通过`);

        if (successCount === totalCount) {
            console.log('🎉 所有测试通过！1060指令实现正确！');
        } else {
            console.log('⚠️ 部分测试失败，请检查实现。');
        }
    }

    async runAllTests() {
        console.log('🚀 开始测试1060指令 - 药品信息查询功能');
        console.log('='.repeat(60));

        await this.testValidMedicineQuery();
        await this.testNonExistentMedicine();
        await this.testInvalidGidType();
        await this.testMissingGid();
        await this.testAnotherValidMedicine();

        this.printTestResults();
    }
}

// 运行测试
if (require.main === module) {
    const tester = new MedicineInfoTester();
    tester.runAllTests().catch(console.error);
}

module.exports = MedicineInfoTester;
